/*
 * Copyright (C) 2014 hu
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package cn.edu.hfut.dmic.webcollector.ui;

import java.awt.EventQueue;
import java.io.File;
import java.io.IOException;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.spi.LoggingEvent;

import cn.edu.hfut.dmic.webcollector.util.LogUtils;
import cn.edu.hfut.dmic.webcollector.crawler.BreadthCrawler;

/**
 *
 * @author hu
 */
public class BreadthCrawlerUI extends javax.swing.JFrame {

    /**
     * Creates new form BasicCrawlerUI
     */
    BreadthCrawler crawler = new BreadthCrawler();
    int threads = 10;
    int depth = 5;
    public String crawlPath="crawl";
    
    
    public class TextAreaAppender extends AppenderSkeleton implements DocumentListener{
        
        public PatternLayout layout;
        
        public TextAreaAppender(){
            logArea.getDocument().addDocumentListener(this);
            layout=new PatternLayout("%d{yyyy-MM-dd HH:mm:ss} %p %c %x - %m%n ");
        }

        @Override
        protected void append(final LoggingEvent le) {
             EventQueue.invokeLater(new Runnable(){

                    @Override
                    public void run() {
                        logArea.append(layout.format(le));
                    }
                    
                });
        }

        @Override
        public void close() {
        }

        @Override
        public boolean requiresLayout() {
            return false;
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
        }
        
    }
    
    
               
        
        
    

    public BreadthCrawlerUI() {
        initComponents();
        LogUtils.getLogger().removeAppender("default");
        LogUtils.getLogger().addAppender(new TextAreaAppender());
        
        
        /*
        LogUtils.handler=new Handler(){

            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg); //To change body of generated methods, choose Tools | Templates.
                if(!msg.obj.getClass().isArray()){
                    return;
                }
                
                final String[] infos=(String[]) msg.obj;
                if(infos.length<3){
                    return;
                }
                EventQueue.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        tablemodel.addRow(new String[]{infos[0],infos[2]});
                   
                       // tb_status.scrollRectToVisible(tb_status.getCellRect(tb_status.getRowCount()-1,0,true));
                
                    }
                });
               
            }
        
            
        };*/
        File f = new File("download");
        txt_path.setText(f.getAbsolutePath());
        
        txt_threads.setText(threads + "");
        txt_depth.setText(depth + "");
        String help = "1.种子\n"
                +"至少添加一个种子（种子即爬虫的起始页面的网址)。\n"
                +"如果要爬去整个站点，可以用站点主页的网址作为种子。\n"
                + "例如爬取新华网，就也可以添加一个种子：\n"
                +"    http://www.xinhuanet.com/\n\n"
                +"2.正则\n"
                + "正则起到约束爬取页面的URL的作用。\n"
                +"至少添加一个\"允许的正则\"\n\n"
                +"3.本地路径\n"
                +"本地路径制定爬取页面在本地的存放路径\n";

        output(help);
        //crawler.addRegex("http://.*xinhuanet.com/.*");

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        txt_seed = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        btn_addseed = new javax.swing.JButton();
        txt_pregex = new javax.swing.JTextField();
        btn_addpregex = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        txt_output = new javax.swing.JTextArea();
        jLabel3 = new javax.swing.JLabel();
        txt_path = new javax.swing.JTextField();
        btn_start = new javax.swing.JButton();
        btn_stop = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        txt_threads = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        txt_nregex = new javax.swing.JTextField();
        btn_addnregex = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        txt_depth = new javax.swing.JTextField();
        jScrollPane3 = new javax.swing.JScrollPane();
        logArea = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("基础爬虫");

        jLabel1.setText("种子:");

        jLabel2.setText("允许的正则:");

        btn_addseed.setText("添加");
        btn_addseed.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_addseedActionPerformed(evt);
            }
        });

        btn_addpregex.setText("添加");
        btn_addpregex.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_addpregexActionPerformed(evt);
            }
        });

        txt_output.setColumns(20);
        txt_output.setRows(5);
        jScrollPane2.setViewportView(txt_output);

        jLabel3.setText("本地路径:");

        txt_path.setText("download");
        txt_path.setToolTipText("");

        btn_start.setText("开始");
        btn_start.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_startActionPerformed(evt);
            }
        });

        btn_stop.setText("停止");
        btn_stop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_stopActionPerformed(evt);
            }
        });

        jLabel4.setText("线程数:");

        jLabel5.setText("禁止的正则(可选):");
        jLabel5.setToolTipText("");

        btn_addnregex.setText("添加");
        btn_addnregex.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_addnregexActionPerformed(evt);
            }
        });

        jLabel6.setText("深度:");

        logArea.setColumns(20);
        logArea.setRows(5);
        jScrollPane3.setViewportView(logArea);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(76, 76, 76)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel4)
                                    .addComponent(jLabel5)
                                    .addComponent(jLabel6))
                                .addGap(27, 27, 27)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(txt_nregex, javax.swing.GroupLayout.DEFAULT_SIZE, 373, Short.MAX_VALUE)
                                    .addComponent(txt_threads)
                                    .addComponent(txt_pregex, javax.swing.GroupLayout.DEFAULT_SIZE, 373, Short.MAX_VALUE)
                                    .addComponent(txt_seed)
                                    .addComponent(txt_path, javax.swing.GroupLayout.DEFAULT_SIZE, 373, Short.MAX_VALUE)
                                    .addComponent(txt_depth))
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addGroup(layout.createSequentialGroup()
                                            .addGap(35, 35, 35)
                                            .addComponent(btn_addseed))
                                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(btn_addpregex)))
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addGap(5, 5, 5)
                                        .addComponent(btn_addnregex))))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btn_start)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btn_stop)))
                        .addGap(71, 71, 71)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 414, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane3))
                .addContainerGap(83, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txt_seed, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btn_addseed)
                            .addComponent(jLabel1))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addComponent(btn_addpregex)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btn_addnregex)
                                .addGap(115, 115, 115))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(6, 6, 6)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel2)
                                    .addComponent(txt_pregex, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel5)
                                    .addComponent(txt_nregex, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel3)
                                    .addComponent(txt_path, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel4)
                                    .addComponent(txt_threads, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel6)
                                    .addComponent(txt_depth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(50, 50, 50)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(btn_start)
                                    .addComponent(btn_stop)))))
                    .addComponent(jScrollPane2))
                .addGap(39, 39, 39)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 479, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(50, 50, 50))
        );

        jLabel2.getAccessibleContext().setAccessibleName("允许的正则(可选)：");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btn_addseedActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_addseedActionPerformed
        // TODO add your handling code here:
        String seed = txt_seed.getText();
        crawler.addSeed(seed);
        output("添加种子:" + seed);
    }//GEN-LAST:event_btn_addseedActionPerformed

    private void btn_startActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_startActionPerformed
        // TODO add your handling code here:
        final String localpath = txt_path.getText().trim();
 
       
        Thread crawlthread = new Thread() {
            @Override
            public void run() {

                crawler.setRoot(localpath);
                crawler.setResumable(false);
                crawler.setCrawlPath(crawlPath);
                try {
                    depth = Integer.valueOf(txt_depth.getText());
                    threads = Integer.valueOf(txt_threads.getText());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    crawler.start(depth);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        };
        crawlthread.start();

        btn_start.setEnabled(false);
        output("开始爬取，请前往" + localpath + "文件夹查看爬取文件,不要关闭此窗口！");
    }//GEN-LAST:event_btn_startActionPerformed

    private void btn_addpregexActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_addpregexActionPerformed
        // TODO add your handling code here:
        String regex = txt_pregex.getText();
        crawler.addRegex("+" + regex);
        output("添加正例正则:" + regex);
    }//GEN-LAST:event_btn_addpregexActionPerformed

    private void output(String line) {
        txt_output.append(line + "\n");
    }

    private void btn_stopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_stopActionPerformed
        // TODO add your handling code here:
        btn_start.setEnabled(true);
        try{
            crawler.stop();
            output("停止");
        }catch(Exception ex){
            ex.printStackTrace();
        }

    }//GEN-LAST:event_btn_stopActionPerformed

    private void btn_addnregexActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_addnregexActionPerformed
        // TODO add your handling code here:
        String regex = txt_pregex.getText();
        crawler.addRegex("-" + regex);
        output("添加反例正则:" + regex);
    }//GEN-LAST:event_btn_addnregexActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(BreadthCrawlerUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(BreadthCrawlerUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(BreadthCrawlerUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(BreadthCrawlerUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new BreadthCrawlerUI().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_addnregex;
    private javax.swing.JButton btn_addpregex;
    private javax.swing.JButton btn_addseed;
    private javax.swing.JButton btn_start;
    private javax.swing.JButton btn_stop;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextArea logArea;
    private javax.swing.JTextField txt_depth;
    private javax.swing.JTextField txt_nregex;
    private javax.swing.JTextArea txt_output;
    private javax.swing.JTextField txt_path;
    private javax.swing.JTextField txt_pregex;
    private javax.swing.JTextField txt_seed;
    private javax.swing.JTextField txt_threads;
    // End of variables declaration//GEN-END:variables
}
